<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/7/13
 * Time: 9:18
 */

namespace app\index\controller;


class Lottery
{
    public function Index(){

        return view();
    }
    public function Lottery(){

        $arr = array();
        $pr = array();
        $prizeArr = array(
            '0' => array('id'=>1,'prize'=>'平板电脑','v'=>1),
            '1' => array('id'=>2,'prize'=>'数码相机','v'=>5),
            '2' => array('id'=>3,'prize'=>'音箱设备','v'=>10),
            '3' => array('id'=>4,'prize'=>'4G优盘','v'=>12),
            '4' => array('id'=>5,'prize'=>'10Q币','v'=>22),
            '5' => array('id'=>6,'prize'=>'下次没准就能抽中哦','v'=>50),
        );

        foreach($prizeArr as $key => $val){
            $arr[$val['id']] = $val['v'];
        }

        //跟据概率获取奖项id
        $rid = $this->getRand($arr);

        //将中奖奖品保存在数组$res['yes']中,而剩下的未中奖的信息保存在$res['no']中
        $res['yes'] = $prizeArr[$rid-1]['prize']; //中奖项
        unset($prizeArr[$rid-1]); //将中奖项剔除，剩下为未中奖项
        shuffle($prizeArr);  //打乱数组顺序
        for($i=0;$i<count($prizeArr);$i++){
            $pr[] = $prizeArr[$i]['prize'];
        }
        $res['no'] = $pr;
        echo json_encode($res,JSON_UNESCAPED_UNICODE);

    }
    /**
     * 概率计算函数
     * @param $proArr
     * @return int|string
     */
    public function getRand($proArr){
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur){
            $randNum = mt_rand(1,$proSum);
            if($randNum <= $proCur){
                $result = $key;
                break;
            }else{
                $proSum -= $proCur;
            }
        }

        unset($proArr);

        return $result;
    }
}